﻿using System;
using System.Runtime.InteropServices;

namespace UnityEngine.XR.iOS
{
    public class UnityARUtility
    {
        private MeshCollider _meshCollider; //declared to avoid code stripping of class
        private MeshFilter _meshFilter; //declared to avoid code stripping of class

        private static GameObject s_planePrefab = null;

        public static void InitializePlanePrefab(GameObject go)
        {
            s_planePrefab = go;
        }

        public static GameObject CreatePlaneInScene(ARPlaneAnchor arPlaneAnchor)
        {
            GameObject plane;
            if (s_planePrefab != null)
            {
                plane = GameObject.Instantiate(s_planePrefab);
            }
            else
            {
                plane = new GameObject(); //put in a blank gameObject to get at least a transform to manipulate
            }

            plane.name = arPlaneAnchor.identifier;

            return UpdatePlaneWithAnchorTransform(plane, arPlaneAnchor);

        }

        public static GameObject UpdatePlaneWithAnchorTransform(GameObject plane, ARPlaneAnchor arPlaneAnchor)
        {
            //do coordinate conversion from ARKit to Unity
            plane.transform.position = UnityARMatrixOps.GetPosition(arPlaneAnchor.transform);
            plane.transform.rotation = UnityARMatrixOps.GetRotation(arPlaneAnchor.transform);

            MeshFilter meshFilter = plane.GetComponentInChildren<MeshFilter>();

            if (meshFilter != null)
            {
                //since our plane mesh is actually 10mx10m in the world, we scale it here by 0.1f
                meshFilter.gameObject.transform.localScale = new Vector3(arPlaneAnchor.extent.x * 0.1f, arPlaneAnchor.extent.y * 0.1f, arPlaneAnchor.extent.z * 0.1f);

                //convert our center position to unity coords
                meshFilter.gameObject.transform.localPosition = new Vector3(arPlaneAnchor.center.x, arPlaneAnchor.center.y, -arPlaneAnchor.center.z);
            }

            return plane;
        }
    }
}

